﻿using System.Windows;
using System.Windows.Media;
using TextEditor.TextBoxInner.Utils;

namespace TextEditor.TextBoxInner.DrawingElements
{
	internal class SelectionLine : DrawingVisual
	{
		private static readonly Brush SelectionBrush = Brushes.DeepSkyBlue;

		private bool _isVisible;
		private int _startCol;
		private int _endCol;
		private int _line;

		public SelectionLine()
		{
			VisualTextRenderingMode = TextRenderingMode.Aliased;
		}

		public bool IsVisible
		{
			get { return _isVisible; }
		}

		public int LineIndex
		{
			get { return _line; }
		}

		public void SetTop(double topOffset)
		{
			VisualOffset = new Vector(0, topOffset);
		}

		public void ClearContent()
		{
			if (!_isVisible)
				return;

			_isVisible = false;
			Draw();
		}

		public void SetContent(int line, int startCol, int endCol)
		{
			_line = line;

			if (_isVisible && _startCol == startCol && _endCol == endCol)
				return;

			_isVisible = true;
			_startCol = startCol;
			_endCol = endCol;

			Draw();
		}

		public override string ToString()
		{
			return IsVisible ? "Line: " + _line : "Invisible";
		}

		private void Draw()
		{
			DrawingContext drawing = RenderOpen();

			try
			{
				if (_isVisible)
					DrawLine(drawing);
			}
			finally
			{
				drawing.Close();
			}
		}

		private void DrawLine(DrawingContext drawingContext)
		{
			drawingContext.DrawRectangle(SelectionBrush, null, new Rect(_startCol * FontHelper.FontWidth, 0, (_endCol - _startCol) * FontHelper.FontWidth, FontHelper.FontHeight));
		}
	}
}
